<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        table {
            border-collapse: collapse;
            width: 100%;
            height: 150px;
        }

        th,
        td {
            border: 1px solid black;
        }

        /* tr:nth-of-type(even) {
            background-color: aqua;
        } */
        .nav {
            text-align: center;
            background-color: rgb(210, 208, 208);
        }

        .nav a {
            display: inline-block;
            width: 50px;
            height: 50px;
            line-height: 50px;
            text-align: center;
            cursor: pointer;
            /* border: 1px solid black; */
            border-radius: 20%;
            /* color: aqua; */
        }

        .selected {
            background-color: aqua;
            /* border-radius: 50%; */

        }

        tbody a {
            cursor: pointer;
            margin: 0 10px;
        }

        tbody a:hover {
            text-decoration: underline;
        }

        .modal {
            position: fixed;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            background-color: rgba(0, 0, 0, 0.5);
            display: none;
        }

        .modal form {
            position: fixed;
            left: 50%;
            top: 50%;
            width: 300px;
            height: 200px;
            margin-left: -150px;
            margin-top: -100px;
            background-color: white;
            box-sizing: border-box;
            padding: 20px;
        }
    </style>
</head>

<body>
    <h1>首页</h1>
    <table>
        <thead>
            <th>id</th>
            <th>用户名</th>

            <th>创建时间</th>
            <th>更新时间</th>
            <th>操作</th>
        </thead>
        <tbody>

        </tbody>
    </table>
    <div class="nav">
    </div>

    <div class="modal">
        <form name="modifyPassword">
            <div>
                &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;id: <input type="text" name="id">
            </div>
            <div>
                原密码: <input type="text" name="old">
            </div>
            <div>
                新密码: <input type="text" name="new">
            </div>
            <button type="submit">修改</button>
        </form>
    </div>

    <!-- <button>上一页</button>

    <button>下一页</button> -->
    <script>
        const btn = document.querySelectorAll('button');
        const tbody = document.querySelector('tbody');
        const nav = document.querySelector('.nav');
        const form = document.forms[0];
        const modal = document.querySelector('.modal');
        //定义变量
        let pageTotal;//总页数
        let pageSize = 5;//每一页的条数
        let pageCurrent = 1;//当前页数
        getAjax()
        // init()
        nav.onclick = nav_onclick;

        /* 
        判断用户是否已经登录自己的账号
        setRequestHeader  设置请求头，并且将存储的本地数据添加上去
        */
        function getAjax() {
            const xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (this.readyState == 4) {
                    if (this.status == 200) {
                        pageTotal = xhr.response.pageTotal;
                        setPage(pageTotal);
                        setTable(xhr.response.data)
                    }
                    if (this.status == 401) {
                        alert('您登录的信息有误或登录超时\n请重新登录');
                        location.replace('login.html')
                    }
                }
            }
            xhr.open('get', `/admin/get?pageSize=${pageSize}&pageCurrent=${pageCurrent}`, true);
            xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token'));
            xhr.responseType = 'json';
            xhr.send();
        }
        //设置显示时间格式
        /* 
          用来将传过来的时间数据更好的渲染到页面上面
        */
        Date.prototype.format = function (string = 'yyyy-MM-dd hh:mm:ss') {
            console.log(this);
            string = string.replace('yyyy', this.getFullYear());
            string = string.replace('MM', this.getMonth() + 1);
            string = string.replace('dd', this.getDate());
            string = string.replace('hh', this.getHours());
            string = string.replace('mm', this.getMinutes());
            string = string.replace('ss', this.getSeconds());
            return string;
        }
        //写表格数据
        /* 
          使用data数组，添加forEach来遍历数组
          item为数组中的每一个对象元素
        */
        function setTable(data) {
            //清空表格内的内容
            tbody.innerHTML = '';
            //遍历添加tr，td
            data.forEach(item => {
                //添加id编号
                const tr = document.createElement('tr');
                let td = document.createElement('td');
                td.innerHTML = item._id;
                tr.appendChild(td);

                //添加用户名
                td = document.createElement('td');
                td.innerHTML = item.userName;
                tr.appendChild(td);

                //添加创建时间
                td = document.createElement('td');
                td.innerHTML = new Date(item.ct).format('yyyy-MM-dd hh:mm:ss');
                tr.appendChild(td);

                //添加更新时间
                td = document.createElement('td');
                td.innerHTML = new Date(item.ut).format('yyyy-MM-dd hh:mm:ss');
                tr.appendChild(td);

                //创建删除和修改
                td = document.createElement('td');
                td.innerHTML = `<a data-id='${item._id}' data-type='remove'>删除</a><a data-id='${item._id}' data-type='modify'>修改</a>`;
                tr.appendChild(td);
                //添加删除时间
                td.onclick = td_click;

                //添加
                tbody.appendChild(tr);
            });

        }
        /* 
          分页栏函数
          给分页栏通过js渲染页面
          并且将页数添加到对应的分页栏的自定义属性当中
        */
        function setPage(pageTotal) {
            let s = '';
            s += `<a data-index='1'>首页</a>`
            s += `<a data-index='${pageCurrent - 1}'>上一页</a>`
            for (let i = 1; i <= pageTotal; i++) {
                s += `<a data-index='${i}'>${i}</a>`

            }
            s += `<a data-index='${pageCurrent + 1}'>下一页</a>`
            s += `<a data-index='${pageTotal}'>尾页</a>`
            nav.innerHTML = s;
            [...document.querySelectorAll(`[data-index='${pageCurrent}']`)].forEach(item => {
                item.classList.add('selected')
            });
        }

        //事件委托 
        /* 
          分页栏的点击事件
        */
        function nav_onclick(e) {
            if (e.target.nodeName == 'A') {
                let index = e.target.dataset.index * 1;

                if (index < 1) {
                    alert('已经第一页了');
                    return
                }
                if (index > pageTotal) {
                    alert('已经是最后一页了');
                    return
                }
                pageCurrent = index;
                getAjax()
            }
        }

        //删除事件  和  修改事件
        function td_click(e) {
            if (e.target.nodeName == "A") {
                let id = e.target.dataset.id;
                //移除
                if (e.target.dataset.type == 'remove') {
                    if (confirm('您确定要删除当前这个信息吗')) {
                        const xhr = new XMLHttpRequest();
                        xhr.onreadystatechange = function () {
                            if (this.readyState == 4) {
                                if (this.status == 200) {
                                    if (xhr.response.flag) {
                                        getAjax()
                                    }
                                }
                                if (this.status == 401) {
                                    alert('您登录的信息有误或登录超时\n请重新登录');
                                    location.replace('login.html')
                                }
                            }
                        }
                        xhr.open('get', `/admin/remove?id=${id}`, true);
                        xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token'));
                        xhr.responseType = 'json';
                        xhr.send();
                    }
                }
                if (e.target.dataset.type == 'modify') {
                    modal.style.display = 'block';


                    form.id.value = e.target.dataset.id;
                    form.onsubmit = function (e) {
                        e.preventDefault();
                        const xhr = new XMLHttpRequest();
                        xhr.onreadystatechange = function () {
                            if (this.readyState == 4) {
                                if (this.status == 200) {
                                    if (xhr.response.flag) {
                                        alert('数据重置成功')
                                    } else {
                                        alert(xhr.response.msg)
                                    }
                                }
                                modal.style.display = 'none';
                                form.reset();
                                if (this.status == 401) {
                                    alert('您登录的信息有误或登录超时\n请重新登录');
                                    location.replace('login.html')
                                }
                            }
                        }
                        xhr.open('post', `/admin/modifyPassword`, true);
                        xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token'));
                        xhr.setRequestHeader('Content-Type', 'application/json');
                        xhr.responseType = 'json';
                        xhr.send(JSON.stringify({
                            id,
                            oldpassword: form.old.value,
                            newpassword: form.new.value,
                        }));
                    }

                }
            }
        }
    </script>
</body>

</html>